package com.kapcb.ruleengine.core;

import com.kapcb.ruleengine.api.Facts;
import com.kapcb.ruleengine.api.Rule;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <a>Title: CompositeRule </a>
 * <a>Author: Kapcb <a>
 * <a>Description: CompositeRule <a>
 *
 * @author Kapcb
 * @version 1.0
 * @date 2024/8/17 10:23
 * @since 1.0
 */
public abstract class CompositeRule extends AbstractRule {

    protected List<Rule> rules = new ArrayList<>();

    private boolean isSorted = false;

    public CompositeRule priority(int priority) {
        this.priority = priority;
        return this;
    }

    public CompositeRule name(String name) {
        this.name = name;
        return this;
    }

    public CompositeRule() {

    }

    @Override
    public boolean apply(Facts facts) {
        sort();
        return doApply(facts);
    }

    protected abstract boolean doApply(Facts facts);

    protected void sort() {
        if (!isSorted) {
//            LOGGER.debug(this.name + " before sort:" + rules);
            Collections.sort(rules);
//            LOGGER.debug(this.name + " after sort:" + rules);
            isSorted = true;
        }
    }

}
